package mysql

import (
	"errors"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
)

func WithMysql(hand func(db *gorm.DB) error) error {
	dsn := fmt.Sprintf("root:123456@tcp(mysql:3306)/shop?charset=utf8mb4&parseTime=True&loc=Local")
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		return errors.New("mysql client failed,error: " + err.Error())
	}
	fmt.Println("mysql connection successful")
	defer func() {
		fmt.Println("关闭连接")
		dd, _ := db.DB()
		err := dd.Close()
		if err != nil {
			log.Printf("msyql close %v", err)
			return
		}
	}()
	return hand(db)
}
